package com.test.demo.service.impl;

import com.test.demo.common.Constants;
import com.test.demo.common.result.Result;
import com.test.demo.common.result.ResultCode;
import com.test.demo.entity.UserInfo;
import com.test.demo.entity.dto.UserInfoDTO;
import com.test.demo.enums.StatusEnum;
import com.test.demo.mapper.UserMapper;
import com.test.demo.service.UserService;
import com.test.demo.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Result register(UserInfoDTO userInfoDTO) {
        String mobilePhone = userInfoDTO.getMobilePhone();
        UserInfo userInfo = userMapper.selectByMobilePhone(mobilePhone);
        if (userInfo != null) {
            return Result.fail(ResultCode.USER_EXISTS.code, "手机号已注册");
        }
        userInfo = new UserInfo();
        userInfo.setMobilePhone(mobilePhone);
        userInfo.setStatus(StatusEnum.NORMAL.getCode());
        userMapper.insert(userInfo);
        Long userId = userInfo.getId();
        String token = JwtUtil.generateAppToken(userId);
        redisTemplate.opsForValue().set(Constants.APP_TOKEN + userId, token, 15, TimeUnit.DAYS);
        Map<String, Object> map = new HashMap<>();
        map.put("userInfo", userInfo);
        map.put("token", token);
        return Result.success(map);
    }
}
